import json
import os
import platform

import allure
import pytest

from tests.utils.logUtil import log


def set_report_env_on_results(env_path: str):
    """
    在allure-results报告的目录下生成一个写入了环境信息的文件：environment.properties(注意：不能放置中文，否则会出现乱码)
    @return:
    """
    # 需要写入的环境信息
    allure_env = {
        'OperatingEnvironment': "testing",
        'BaseUrl': "localhost",
        'PythonVersion': platform.python_version(),
        'Platform': platform.platform(),
        'PytestVersion': pytest.__version__,
    }
    os.makedirs(os.path.dirname(env_path), exist_ok=True)
    with open(env_path, 'w', encoding='utf-8') as f:
        for _k, _v in allure_env.items():
            f.write(f'{_k}={_v}\n')


def set_report_execute_on_results(env_path: str):
    """
    在allure-results报告的目录下生成一个写入了执行人的文件：executor.json
    @return:
    """
    # 需要写入的环境信息
    allure_executor = {
        "name": "Milo",
        # 类型
        "type": "gitlab",
        # allure报告的地址
        "url": "localhost",
        "buildOrder": 3,
        "buildName": "allure-report_deploy#1",
        "buildUrl": "http://helloqa.com/#1",
        "reportUrl": "http://helloqa.com/#1/AllureReport",
        "reportName": "Milo Allure Report"
    }
    os.makedirs(os.path.dirname(env_path), exist_ok=True)
    with open(env_path, 'w', encoding='utf-8') as f:
        f.write(str(json.dumps(allure_executor, ensure_ascii=False, indent=4)))


def attach_file_to_allure(file_path, attachment_name, attachment_type):
    """
    辅助函数用于检查文件是否存在、记录信息并将其附加到 Allure.
    :param file_path: 要附加的文件的路径.
    :param attachment_name: 要在 Allure 报告中显示的名称.
    :param attachment_type: 文件的类型（例如 PNG、JPG）.
    """
    log.info(f"Attempting to attach file: {file_path}")

    if os.path.exists(file_path):
        # Attach the file to Allure report
        allure.attach.file(
            source=file_path,
            name=attachment_name,
            attachment_type=attachment_type
        )
        log.info(f"File attached successfully: {file_path}")
    else:
        log.error(f"File not found: {file_path}")
